package com.elvt.server.config.security;

import com.elvt.server.config.JwtAuthencationTokenFilter;
import com.elvt.server.config.security.component.CustomerFilter;
import com.elvt.server.config.security.component.CustomerUrlDecisionManager;
import com.elvt.server.pojo.Admin;
import com.elvt.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @Author 作者： elvt
 * @Data 时间：2022/5/22
 * @packageName 包路径： ybg_back_end
 * @Desciption 说明： security配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
    @Autowired
    private RestfulAccessDeinedHand restfulAccessDeinedHand;
    @Autowired
    private CustomerFilter customerFilter;
    @Autowired
    private CustomerUrlDecisionManager customerUrlDecisionManager;


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login",
                "/logout",
                "/css/**",
                "/js/**",
                "/index",
                "favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/captcha",
                "/ws/**"
        );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用jwt验证，不需要开启csrf
        http.csrf()
               .disable()
                //基于token 不需要session
               .sessionManagement()
               .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //.and就可以继续连式编程写代码
                .and()
                .authorizeRequests()

                //所有的路径都要登录才可以访问
                .anyRequest()
                .authenticated()
                //动态权限配置
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                            object.setAccessDecisionManager(customerUrlDecisionManager);
                            object.setSecurityMetadataSource(customerFilter);
                        return object;
                    }
                })
                .and()
                //关闭缓存，
                .headers()
                .cacheControl();
        //添加jwt 登录授权拦截器
        http.addFilterBefore(jwtAuthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录接口返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeinedHand)
                .authenticationEntryPoint(restAuthorizationEntryPoint);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService(){

        return username->{
            Admin admin = adminService.getAdminByUserName(username);
            if (null!=admin){
                //如果admin不空的花，则从数据库中查询返回角色信息
                admin.setRoles(adminService.getRolesByAdmin(admin.getId()));
                return admin;

            }
           throw new UsernameNotFoundException("用户名或者密码不正确");
        };
    }

    @Bean
    public PasswordEncoder passwordEncoder(){

        return new  BCryptPasswordEncoder();
    }
    @Bean
    public JwtAuthencationTokenFilter jwtAuthencationTokenFilter(){
        return new JwtAuthencationTokenFilter();
    }
}
